package com.lecture.java8.excel.dyr.m;

import com.alibaba.excel.EasyExcel;
import com.lecture.java8.excel.DemoDataListener;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Test0806 {
    public static void main(String[] args) {
        String dir = "D:\\study\\tmp\\0806\\";


        String resultPath = dir + "大数据.xlsx";
        DemoDataListener<Model0806> dataResultListener = new DemoDataListener<>();
        EasyExcel.read(resultPath, Model0806.class,dataResultListener).sheet().doRead();
        //全要素生产率
        List<Model0806> resultList = dataResultListener.getDataList();
        Set<String> codeSet = new HashSet<>();
        for (Model0806 model0724 : resultList) {
            if (model0724.getB().contains("st") || model0724.getB().contains("ST")) {
                codeSet.add(model0724.getA());
            }
        }
        List<Model0806> result1 = new ArrayList<>();
        for (Model0806 model0724 : resultList) {
            if (!codeSet.contains(model0724.getA())) {
                String year = model0724.getC().substring(0,4);
                if ("2023".equals(year)) {
                    continue;
                }
                model0724.setK(year);
                result1.add(model0724);
            }
        }
        result1 = filterCompleteYears(result1,2012,2022);



        EasyExcel.write( dir + "0806结果.xlsx", Model0806.class)
                .sheet("a").doWrite(result1);
    }

    public static List<Model0806> filterCompleteYears(List<Model0806> list, int startYear, int endYear) {
        Set<Integer> requiredYears = IntStream.rangeClosed(startYear, endYear)
                .boxed()
                .collect(Collectors.toSet());
        Set<String> s = new HashSet<>();
        s.add("2012");
        s.add("2013");
        s.add("2014");
        s.add("2015");
        s.add("2016");
        s.add("2017");
        s.add("2018");
        s.add("2019");
        s.add("2020");
        s.add("2021");
        s.add("2022");

        // Group by code and filter
        Map<String, Set<String>> codeToYearsMap = list.stream()
                .collect(Collectors.groupingBy(
                        Model0806::getA,
                        Collectors.mapping(Model0806::getK, Collectors.toSet())
                ));


        Set<String> validCodes = codeToYearsMap.entrySet().stream()
                .filter(entry -> entry.getValue().equals(s))
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());

        // Filter original list by valid codes
        return list.stream()
                .filter(obj -> validCodes.contains(obj.getA()))
                .collect(Collectors.toList());
    }
}
